    //
//  CustomWebViewController.m
//  Vgo
//
//  Created by 21CN Vgo on 10-10-18.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustomWebViewController.h"
#import "CmnMacro.h"
#import "CmnFunc.h"
#import <QuartzCore/QuartzCore.h>

@implementation CustomWebViewController

@synthesize webView;
@synthesize loadingView;
@synthesize networkStateView;
@synthesize loadingSubView;
@synthesize showLoading;
@synthesize showContentWhenLoading;
@synthesize delegate;
@synthesize bounces;
@synthesize state;
@synthesize currentUrl;

- (void)setBounces:(BOOL)_bounces
{
	bounces = _bounces;
	
	if ([self isViewLoaded])
	{
		UIScrollView* sv = nil;
		for (UIView* v in self.webView.subviews)
		{
			if([v isKindOfClass:[UIScrollView class] ])
			{
				sv = (UIScrollView*) v;
				sv.bounces = bounces;
			}
		}
	}
}

- (void)loadURLString:(NSString *)urlString withBookmark:(NSString *)bookmark
{
	NSString * encoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	encoded = [NSString stringWithFormat:@"%@%@", encoded, bookmark];
	
	NSLog([CmnFunc URLDecode:encoded], nil);
	
	[self loadURL:[NSURL URLWithString:encoded]];
}

- (void)loadURLString:(NSString *)urlString
{
	NSLog([CmnFunc URLDecode:urlString], nil);
	
	NSString * encoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[self loadURL:[NSURL URLWithString:encoded]];
}

- (void)loadURL:(NSURL *)url
{
	if (self.currentUrl != url)
		self.currentUrl = url;
	
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	
	[self.webView loadRequest:request];
	
	[request release];
}

- (void)reload
{
	if (self.state == CWVS_Network)
	{
		[self loadURL:currentUrl];
	}
	else
	{
		[self.webView reload];
	}

}

- (void)setState:(CustomWebViewState)_state
{
	state = _state;
	
	switch (state) {
		case CWVS_Normal:
			loadingView.hidden = networkStateView.hidden = YES;
			webView.hidden = NO;
			break;
		case CWVS_Loading:
			webView.hidden = networkStateView.hidden = YES;
			if (showContentWhenLoading)
			{
				webView.hidden = NO;
			}
			loadingView.hidden = NO;
			break;
		case CWVS_Network:
			networkStateView.hidden = NO;
			webView.hidden = loadingView.hidden = YES;
			break;
		default:
			break;
	}

	if ([delegate respondsToSelector:@selector(webViewStateChanged:)])
	{
		[delegate webViewStateChanged:state];
	}
}

- (id)initWithCoder:(NSCoder *)decoder
{
	self = [super initWithCoder:decoder];
	
	bounces = YES;
	
	return self;
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	self.view.opaque = webView.opaque = NO;
	self.view.backgroundColor = webView.backgroundColor = [UIColor clearColor];

	[self.view addSubview:networkStateView];
	networkStateView.frame = self.view.bounds;
	networkStateView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
	
	[self.view addSubview:loadingView];
	loadingView.frame = self.view.bounds;
	loadingView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);

	self.loadingSubView.layer.cornerRadius = 5.0;
	self.loadingSubView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.loadingSubView.bounds].CGPath;
	self.loadingSubView.layer.shadowOffset = CGSizeMake(0.0, 0.0);
	self.loadingSubView.layer.shadowRadius = 10.0;
	self.loadingSubView.layer.shadowOpacity = 1.0;
	self.loadingSubView.layer.shadowColor = [UIColor blackColor].CGColor;
	
	if (!self.webView.request && self.currentUrl)
		[self loadURL:self.currentUrl];

	[self setState:CWVS_Loading];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    //[super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
	self.webView = nil;
	self.loadingView = nil;
	self.networkStateView = nil;
	self.currentUrl = nil;
	self.loadingSubView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	
	webView.delegate = nil;
	[webView stopLoading];
	
	SAFE_RELEASE(webView);
	SAFE_RELEASE(loadingView);
	SAFE_RELEASE(networkStateView);
	SAFE_RELEASE(currentUrl);
	SAFE_RELEASE(loadingSubView);
    [super dealloc];
}

// return TRUE means already deal
- (BOOL)handleCustomURI:(NSURL *)url
{
	BOOL bRet = NO;
	
	// 判断是否加载完毕
	NSRange range = [[url absoluteString] rangeOfString:@"#closeload"];
	NSLog([url absoluteString], nil);
	if (range.length != 0)
	{
		[self setState:CWVS_Normal];
		bRet = YES;
	}

	if (!bRet && delegate && [delegate respondsToSelector:@selector(handleCustomURI:)])
	{
		id result = [delegate performSelector:@selector(handleCustomURI:) withObject:url];
		bRet = (result == (id)0x1);
	}
	
	return bRet;
}

#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	NSLog(@"UIWebViewNavigationType %d", navigationType);
	
	BOOL bRet = YES;
	
	if (navigationType != UIWebViewNavigationTypeReload && [self handleCustomURI:request.URL])
	{
		bRet = NO;
	}
	else
	{
		BOOL b3GLimited = [[[CmnFunc getCurrentConfigDictionary] valueForKey:@"3GLimited"] boolValue];
		if (b3GLimited)
		{
			if (![CmnFunc checkCanUseWifi])
			{
				[self setState:CWVS_Network];
				
				bRet = NO;
			}
		}
		else if (![CmnFunc checkCanUseNetwork])
		{
			[self setState:CWVS_Network];
			
			bRet = NO;
		}

	}
	
	if (bRet == YES)
	{
		if (self.showLoading)
			[self setState:CWVS_Loading];
		else
			[self setState:CWVS_Normal];
	}
	
	return bRet;
}

- (void)webViewDidStartLoad:(UIWebView *)theWebView
{
	if (self.showLoading)
		[self setState:CWVS_Loading];
	else
		[self setState:CWVS_Normal];
	
	if (delegate && [delegate respondsToSelector:@selector(webViewDidStartLoad:)])
		[delegate performSelector:@selector(webViewDidStartLoad:) withObject:theWebView];
	
//	[theWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
//	NSString *path = [[NSBundle mainBundle] pathForResource:@"NewWindow" ofType:@"js"];
//	NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//	[theWebView stringByEvaluatingJavaScriptFromString: jsCode];
//	
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyLinkTargets();"];
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyWindowOpen();"];
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyFormSubmit();"];
}

- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
//	[theWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
//	NSString *path = [[NSBundle mainBundle] pathForResource:@"NewWindow" ofType:@"js"];
//	NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//	[theWebView stringByEvaluatingJavaScriptFromString: jsCode];
//	
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyLinkTargets();"];
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyWindowOpen();"];
//	[theWebView stringByEvaluatingJavaScriptFromString:@"VgoHD_ModifyFormSubmit();"];
	
	[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
	
	//[[NSURLCache sharedURLCache] removeAllCachedResponses];
	
	[self setState:CWVS_Normal];
	
	if (delegate && [delegate respondsToSelector:@selector(webViewDidFinishLoad:)])
		[delegate performSelector:@selector(webViewDidFinishLoad:) withObject:theWebView];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	NSLog(@"didFailLoadWithError code : %d, desc : %@", [error code], [error localizedDescription]);
	switch ([error code]) {
		case NSURLErrorCancelled:
			break;
		default:
			[self setState:CWVS_Network];
			break;
	}
}

- (void)showNormalState
{
	[self setState:CWVS_Normal];
}

@end
